// earthquakes from earthquake.usgs.gov

OpenLayers.Layer.WeEarthquakes = OpenLayers.Class(OpenLayers.Layer.GeoRSS, {
    attribution: "Earthquakes &copy; <a href='http://earthquake.usgs.gov/' target='_blank'>USGS</a>",
    sphericalMercator: true,
    // hide by default
    visibility: false,
    useFeedTitle: false,
    
    date: '1week', // 1hour, 1day, 1week
    //magnitude: 2.5, // 0,1 for 1hour, 0,1,2.5 for 1day, 2.5,5,7 for 7day
    
    initialize: function(name, url, options) {
        OpenLayers.Layer.GeoRSS.prototype.initialize.apply(this, arguments);
        
        //OpenLayers.ProxyHost = 'http://fanghuanweiran.com/cgi-bin/proxy.cgi?url=';
        
        this.name = name ? name : OpenLayers.i18n('WeEarthquakes_name');
        this.projection = new OpenLayers.Projection('EPSG:4326');
        //this.location = 'http://earthquake.usgs.gov/earthquakes/catalogs/eqs' + 
        //                this.date + '-M' + this.magnitude + '.xml';
        this.location = 'http://' + window.location.host + '/earthquakes/' + this.date + '.xml';
        this.icon = new OpenLayers.Icon(
            OpenLayers.ImgPath + 'earthquake.png',
            new OpenLayers.Size(24, 24),
            null,
            function(size) {
                return new OpenLayers.Pixel(-(size.w/2), -(size.h/2));
            }
        );
        this.popupSize = new OpenLayers.Size(300, 60);
    },
    
    /**
     * Method: parseData
     * Parse the data returned from the Events call.
     *
     * Parameters:
     * ajaxRequest - {<OpenLayers.Request.XMLHttpRequest>} 
     */
    parseData: function(ajaxRequest) {
        var doc = ajaxRequest.responseXML;
        if (!doc || !doc.documentElement) {
            doc = OpenLayers.Format.XML.prototype.read(ajaxRequest.responseText);
        }
        
        if (this.useFeedTitle) {
            var name = null;
            try {
                name = doc.getElementsByTagNameNS('*', 'title')[0].firstChild.nodeValue;
            }
            catch (e) {
                name = doc.getElementsByTagName('title')[0].firstChild.nodeValue;
            }
            if (name) {
                this.setName(name);
            }    
        }
       
        var options = {};
        
        OpenLayers.Util.extend(options, this.formatOptions);
        
        if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
            options.externalProjection = this.projection;
            options.internalProjection = this.map.getProjectionObject();
        }    
        
        var format = new OpenLayers.Format.GeoRSS(options);
        var features = format.read(doc);
        
        for (var i=0, len=features.length; i<len; i++) {
            var data = {};
            var feature = features[i];
            
            // we don't support features with no geometry in the GeoRSS
            // layer at this time. 
            if (!feature.geometry) {
                continue;
            }    
            
            var title = feature.attributes.title ? 
                         feature.attributes.title : "Untitled";
            
            var description = feature.attributes.description ? 
                         feature.attributes.description : "No description.";
            
            var link = feature.attributes.link ? feature.attributes.link : "";

            var location = feature.geometry.getBounds().getCenterLonLat();
            
            
            data.icon = this.icon == null ? 
                                     OpenLayers.Marker.defaultIcon() : 
                                     this.icon.clone();
            var mag = parseInt(feature.attributes.title.slice(2), 10);
            
            if (mag > 0) {
                data.icon.size.w = data.icon.size.h = 6*mag;
            } else {
                data.icon.size.w = data.icon.size.h = 6;
            }
            
            data.popupSize = this.popupSize ? 
                             this.popupSize.clone() :
                             new OpenLayers.Size(250, 120);
            
            if (title || description) {
                // we have supplemental data, store them.
                data.title = title;
                data.description = description;
            
                var contentHTML = '<div class="olLayerGeoRSSClose">[X]</div>'; 
                contentHTML += '<div class="olLayerGeoRSSTitle">';
                if (link) {
                    contentHTML += '<a class="link" href="'+link+'" target="_blank">';
                }
                contentHTML += title;
                if (link) {
                    contentHTML += '</a>';
                }
                contentHTML += '</div>';
                contentHTML += '<div style="" class="olLayerGeoRSSDescription">';
                contentHTML += description;
                contentHTML += '</div>';
                data['popupContentHTML'] = contentHTML;                
            }
            var feature = new OpenLayers.Feature(this, location, data);
            this.features.push(feature);
            var marker = feature.createMarker();
            marker.events.register('click', feature, this.markerClick);
            this.addMarker(marker);
            if (marker.icon.imageDiv) {
                marker.icon.imageDiv.style.cursor = 'pointer';
            }
        }
        this.events.triggerEvent("loadend");
    },
    
    /**
     * Method: markerClick
     *
     * Parameters:
     * evt - {Event} 
     */
    markerClick: function(evt) {
        var sameMarkerClicked = (this == this.layer.selectedFeature);
        this.layer.selectedFeature = (!sameMarkerClicked) ? this : null;
        for(var i=0, len=this.layer.map.popups.length; i<len; i++) {
            this.layer.map.removePopup(this.layer.map.popups[i]);
        }
        if (!sameMarkerClicked) {
            var popup = this.createPopup();
            OpenLayers.Event.observe(popup.div, "click",
                OpenLayers.Function.bind(function() { 
                    for(var i=0, len=this.layer.map.popups.length; i<len; i++) { 
                        this.layer.map.removePopup(this.layer.map.popups[i]); 
                    }
                    this.layer.selectedFeature = null;
                }, this)
            );
            this.layer.map.addPopup(popup); 
        }
        OpenLayers.Event.stop(evt);
    },

    CLASS_NAME: 'OpenLayers.Layer.WeEarthquakes'
});

OpenLayers.Layer.WeEarthquakesHourly = OpenLayers.Class(OpenLayers.Layer.WeEarthquakes, {
    date: '1hour', // 1hour, 1day, 7day
    //magnitude: 0, // 0,1 for 1hour, 0,1,2.5 for 1day, 2.5,5,7 for 7day
    
    initialize: function(name, url, options) {
        OpenLayers.Layer.WeEarthquakes.prototype.initialize.apply(this, arguments);
        
        this.name = name ? name : OpenLayers.i18n('WeEarthquakes_hourly');
        this.events.register('visibilitychanged', this, this.onVisibilityChanged);
        this.firstDraw = true;
        this.loaded = false;
    },
    
    // force reload data when re-visible
    onVisibilityChanged: function(evt) {
        if (this.getVisibility()) {
            // do not load twice of first drawing
            if (this.firstDraw) {
                this.firstDraw = false;
            } else {
                if (this.loaded) {
                    this.loaded = false;
                    this.clearFeatures();
                    this.clearMarkers();
                    this.loadRSS();
                }
            }
        } else {
            if (this.firstDraw) {
                this.firstDraw = false;
            }
        }
    },
});

OpenLayers.Layer.WeEarthquakesDaily = OpenLayers.Class(OpenLayers.Layer.WeEarthquakes, {
    date: '1day', // 1hour, 1day, 7day
    //magnitude: 0, // 0,1 for 1hour, 0,1,2.5 for 1day, 2.5,5,7 for 7day
    
    initialize: function(name, url, options) {
        OpenLayers.Layer.WeEarthquakes.prototype.initialize.apply(this, arguments);
        
        this.name = name ? name : OpenLayers.i18n('WeEarthquakes_daily');
    },
});

OpenLayers.Layer.WeEarthquakesWeekly = OpenLayers.Class(OpenLayers.Layer.WeEarthquakes, {
    date: '1week', // 1hour, 1day, 1week
    //magnitude: 2.5, // 0,1 for 1hour, 0,1,2.5 for 1day, 2.5,5,7 for 7day
    
    initialize: function(name, url, options) {
        OpenLayers.Layer.WeEarthquakes.prototype.initialize.apply(this, arguments);
        
        this.name = name ? name : OpenLayers.i18n('WeEarthquakes_weekly');
    },
});

